/*
 * 加密存储工具类
 * @Author: bobo
 * @Date: 2021-01-08 14:28:55
 */
import CacheUtil from '@/utils/CacheUtil'
import CryptoJS from 'crypto-js'
// AES-128-CBC偏移量
const KEY_AES_SECRET = "abcdefgabcdefg12";
const KEY_AES_IV = "abcdefgabcdefg12";
/**
 * aes对称加密
 */
function _encryptAES(data, key, iv) {
  let _key = CryptoJS.enc.Utf8.parse(key);
  let _secretData = CryptoJS.enc.Utf8.parse(data);
  let encrypted = CryptoJS.AES.encrypt(
    _secretData,
    _key, {
      iv: CryptoJS.enc.Utf8.parse(iv),
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    }
  );
  return encrypted.toString();
}
/**
 * aes对称解密
 */
function _decryptAES(data, key, iv) {
  let _key = CryptoJS.enc.Utf8.parse(key);
  let decrypt = CryptoJS.AES.decrypt(
    data,
    _key, {
      iv: CryptoJS.enc.Utf8.parse(iv),
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}


function _buildKey(key) {
  if (process.env.NODE_ENV === 'development') {
    return key;
  } else {
    return CryptoJS.MD5(key).toString()
  }
}

function _encodeData(data) {
  if (process.env.NODE_ENV === 'development') {
    return data;
  } else {
    return _encryptAES(data, KEY_AES_SECRET, KEY_AES_IV)
  }
}

function _decodeData(data) {
  if (process.env.NODE_ENV === 'development') {
    return data;
  } else {
    return _decryptAES(data, KEY_AES_SECRET, KEY_AES_IV)
  }
}

export default {
  /**
   * 缓存数据
   * @param {string} key 关键字
   * @param {string} token 授权token的值
   * @param {number} expire 过期时间，单位:秒  -1永久存储
   */
  save(key, data, expire) {
    const encodeKey = _buildKey(key);
    const encodeData = _encodeData(data)
    CacheUtil.setExp(encodeKey, encodeData, expire || -1)
  },
  /**
   * 获取数据
   * @param {string} key 关键字
   */
  get(key) {
    const encodeKey = _buildKey(key)
    const cacheData = CacheUtil.getExp(encodeKey);

    //判断缓存token是否过期，若过期，内存中缓存的token置空
    if (cacheData == null) {
      return null;
    } else {
      return _decodeData(cacheData)
    }
  },
  remove(key) {
    CacheUtil.remove(_buildKey(key));
  }

}